package models

import (
	"gorm.io/gorm/schema"
	"time"
)

// OptimisticLock 乐观锁
type OptimisticLock struct {
	Id int64 `json:"id" gorm:"primaryKey"`
	SqlTimeFields

	LockName   string     `json:"lock_name" gorm:"type:varchar(64);index:idx_name"` //锁名
	LockedAt   *time.Time `json:"lock_at,omitempty" gorm:"type:datetime"`           //锁定时间
	UnLockedAt *time.Time `json:"unlock_at,omitempty" gorm:"type:datetime"`         //解锁时间

	LockHost string `json:"lock_host" gorm:"type:varchar(32)"` //锁所在主机信息

	Timeout int64 `json:"timeout"` //超时时间，单位：秒

	Status int `json:"status" gorm:"type:tinyint"` //锁状态,0:未锁定,1:已锁

}

func (r *OptimisticLock) TableName(namer schema.Namer) string {
	return namer.TableName("lock_optimistic")
}

func (l *OptimisticLock) IsLock() bool {
	if l.LockedAt == nil {
		return false
	}
	expireTime := l.LockedAt.Add(time.Second * time.Duration(l.Timeout))

	if l.Status == 1 && expireTime.UnixNano() > time.Now().UnixNano() {
		//锁中
		return true
	}

	//未锁
	return false
}
